package com.ferryc.tcc.impl;

import com.ferryc.entity.Stroage;
import com.ferryc.entity.StroageDetail;
import com.ferryc.exception.HandleException;
import com.ferryc.exception.UnderstockException;
import com.ferryc.mapper.StroageDetailMapper;
import com.ferryc.mapper.StroageMapper;
import com.ferryc.tcc.IStroageTccService;
import lombok.extern.slf4j.Slf4j;
import org.bytesoft.compensable.Compensable;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.Date;
import java.util.List;

/**
 * Created by Ferry Chen on 2019/11/19.
 */
@Slf4j
@Compensable(interfaceClass = IStroageTccService.class, confirmableKey = "stroageServiceComfirm", cancellableKey = "stroageServiceCancel")
@Service("stroageTccService")
public class StroageTccServiceImpl implements IStroageTccService {

    @Autowired
    private StroageMapper stroageMapper;
    @Autowired
    private StroageDetailMapper stroageDetailMapper;

    @Transactional
    @Override
    public void consume(Stroage stroage) {
        log.info("try...");
        Stroage qs = new Stroage();
        qs.setProductId(stroage.getProductId());
        List<Stroage> list = stroageMapper.queryList(qs);
        if (!CollectionUtils.isEmpty(list)) {
            if (list.get(0).getCount() < stroage.getCount()) {
                throw new UnderstockException();
            }
            saveDetail("3", list.get(0).getId(), stroage.getCount());
            stroage.setFrozen(stroage.getCount());
            stroage.setCount(list.get(0).getCount() - stroage.getCount());
            stroage.setUpdateTime(new Date());
            stroage.setId(list.get(0).getId());
            int result = stroageMapper.updateStroage(stroage);
            if (1 != result) {
                throw new HandleException();
            }
        }
    }


    private void saveDetail(String type, String id, int count) {
        StroageDetail sd = new StroageDetail();
        sd.setStroageId(id);
        sd.setType(type);
        sd.setCount(count);
        sd.setInsertTime(new Date());
        stroageDetailMapper.insert(sd);
    }
}
